package com.note.web.controller.monitor;

import com.note.common.annotation.Log;
import com.note.common.core.controller.BaseController;
import com.note.common.core.domain.AjaxResult;
import com.note.common.core.domain.entity.SysUser;
import com.note.common.core.page.TableDataInfo;
import com.note.common.core.redis.RedisCache;
import com.note.common.enums.BusinessType;
import com.note.common.utils.StringUtils;
import com.note.common.utils.mail.MailUtil;
import com.note.common.utils.poi.ExcelUtil;
import com.note.common.utils.uuid.IdUtils;
import com.note.framework.web.service.TokenService;
import com.note.system.domain.SysLogininfor;
import com.note.system.service.ISysLogininforService;
import com.note.system.service.ISysUserService;
import com.note.web.dto.ResetPwd;
import com.note.web.dto.RigisterDTO;
import com.note.web.dto.VerificationCodeDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 系统访问记录
 * 
 * @author ruoyi
 */
@Api("用户登录注册相关")
@RestController
@RequestMapping("/monitor/logininfor")
public class SysLogininforController extends BaseController
{
    @Autowired
    private ISysLogininforService logininforService;
    @Autowired
    RedisCache redisCache;
    @Autowired
    private TokenService tokenService;
    @Autowired
    ISysUserService sysUserService;

    @PreAuthorize("@ss.hasPermi('monitor:logininfor:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysLogininfor logininfor)
    {
        startPage();
        List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
        return getDataTable(list);
    }

    @Log(title = "登录日志", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('monitor:logininfor:export')")
    @GetMapping("/export")
    public AjaxResult export(SysLogininfor logininfor)
    {
        List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
        ExcelUtil<SysLogininfor> util = new ExcelUtil<SysLogininfor>(SysLogininfor.class);
        return util.exportExcel(list, "登录日志");
    }

    @PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')")
    @Log(title = "登录日志", businessType = BusinessType.DELETE)
    @DeleteMapping("/{infoIds}")
    public AjaxResult remove(@PathVariable Long[] infoIds)
    {
        return toAjax(logininforService.deleteLogininforByIds(infoIds));
    }

    @PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')")
    @Log(title = "登录日志", businessType = BusinessType.CLEAN)
    @DeleteMapping("/clean")
    public AjaxResult clean()
    {
        logininforService.cleanLogininfor();
        return AjaxResult.success();
    }


    /**
     *
     * @param sendUserMail
     * @param type 0：注册 1：找回密码时
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name="sendUserMail",value="邮箱",required=true,paramType="string")
    })
    @ResponseBody
    @ApiOperation("获取验证码")
    @PostMapping("/getVerificationCode")
    public AjaxResult getVerificationCode(@RequestParam String sendUserMail, Integer type)
    {
        if(StringUtils.isEmpty(sendUserMail)){
            return AjaxResult.error("邮箱为空");
        }

        if(type == null){
            type = 0;
        }

        try {
            //用户每次调用生成验证码时，生成一个codeId，下次前端传此codeId过来获取验证码作匹配
            String codeId = IdUtils.randomUUID();
            String code = MailUtil.productCode();
            MailUtil.sendSimpleMail(sendUserMail, "您的验证码为:"+code);
            if(type == 0){
                //一分钟验证码过期,注册时存这个
                redisCache.setCacheObject(codeId, code, 1, TimeUnit.MINUTES);
            }else {
                //一分钟验证码过期,找回密码时存这个
                redisCache.setCacheObject(codeId, code+":"+sendUserMail, 1, TimeUnit.MINUTES);
            }

            VerificationCodeDTO verificationCodeDTO = new VerificationCodeDTO();
            verificationCodeDTO.setMainId(codeId);
            return AjaxResult.success(verificationCodeDTO);
        } catch (Exception e) {
            return AjaxResult.error("获取验证码失败");
        }
    }

    @ResponseBody
    @ApiOperation("判断此邮箱是否已经注册过")
    @GetMapping("/judgeIsRigister")
    public AjaxResult judgeIsRigister(String email){
        if(StringUtils.isEmpty(email)){
            return AjaxResult.error("email为空");
        }

        int num = logininforService.getUserForEmail(email);
        if(num == 0){
            return  AjaxResult.success(0);
        }

        return AjaxResult.success(1);
    }


    @ResponseBody
    @ApiOperation("重置密码")
    @PostMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody ResetPwd resetPwd){
        if(StringUtils.isEmpty(resetPwd.getNewPwd()) || StringUtils.isEmpty(resetPwd.getEmail()) || StringUtils.isEmpty(resetPwd.getMainId())){
            return AjaxResult.error("mainId或者验证码或者mainId为空");
        }

        Object cacheObject = redisCache.getCacheObject(resetPwd.getEmail());
        if(cacheObject == null){
            return AjaxResult.error("操作超时了");
        }
        //原本保存的mainId
        String originMainId = (String) cacheObject;
        if(!StringUtils.equalsIgnoreCase(originMainId, resetPwd.getMainId())){
            return AjaxResult.error("mainId 异常");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();


        logininforService.resetPwd(resetPwd.getEmail(), passwordEncoder.encode(resetPwd.getNewPwd()));
        return AjaxResult.success("重置密码成功");
    }

    @ResponseBody
    @ApiOperation("找回密码时点击下一步")
    @GetMapping("/nextStepWhenResetPwd")
    public AjaxResult nextStepWhenResetPwd(String mainId, String code){
        if(StringUtils.isEmpty(mainId) || StringUtils.isEmpty(code)){
            return AjaxResult.error("mainId或者验证码为空");
        }

        Object cacheObject = redisCache.getCacheObject(mainId);
        if(cacheObject == null){
            return AjaxResult.error("验证码已过期");
        }
        //原本保存的验证码
        String cacheObjectStr = (String) cacheObject;
        String originCode = cacheObjectStr.split(":")[0];
        String email = cacheObjectStr.split(":")[1];
        if(!StringUtils.equalsIgnoreCase(code, originCode)){
            return AjaxResult.error("验证码输入错误");
        }

        redisCache.setCacheObject(email, mainId, 1, TimeUnit.MINUTES);
        return AjaxResult.success(mainId);
    }



    @ResponseBody
    @ApiOperation("注册用户")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody RigisterDTO rigisterDTO)
    {
        if(StringUtils.isEmpty(rigisterDTO.getUserName()) || StringUtils.isEmpty(rigisterDTO.getPwd())
        || StringUtils.isEmpty(rigisterDTO.getMainId()) || StringUtils.isEmpty(rigisterDTO.getEmail()) || StringUtils.isEmpty(rigisterDTO.getCode())){
            return AjaxResult.error("用户名,昵称,密码,验证码,mainId 存在空值");
        }

        Object cacheObject = redisCache.getCacheObject(rigisterDTO.getMainId());
        if(cacheObject == null){
            return AjaxResult.error("验证码已过期");
        }
        //原本保存的验证码
        String originCode = (String) cacheObject;
        if(!StringUtils.equalsIgnoreCase(rigisterDTO.getCode(), originCode)){
            return AjaxResult.error("验证码输入错误");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        SysUser sysUser = new SysUser();
        sysUser.setUserName(rigisterDTO.getUserName());
        sysUser.setPassword(passwordEncoder.encode(rigisterDTO.getPwd()));
        sysUser.setEmail(rigisterDTO.getEmail());
        sysUser.setNickName("游客");
        //每个用户的资源秘钥
        String sourceKey = MailUtil.productCode();
        sysUser.setSourceKey(sourceKey);
        try {
            logininforService.register(sysUser);
            return AjaxResult.success("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.success("注册失败");

        }
    }

    /**
     * 往用户邮箱发送资源秘钥
     */
    @ResponseBody
    @ApiOperation("往用户邮箱发送资源秘钥")
    @GetMapping("/sendSourceKeyEmail")
    public AjaxResult sendSourceKeyEmail(Long userId)
    {
        try {

            SysUser sysUser = sysUserService.selectUserById(userId);
            if(StringUtils.isEmpty(sysUser.getEmail())){
                return AjaxResult.error("此用户email 不存在");
            }

            MailUtil.sendSimpleMail(sysUser.getEmail(), "您的密钥为:"+sysUser.getSourceKey());
            return AjaxResult.success("发送邮件成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("发送邮件异常");
        }
    }


}
